package com.hisense.ovcloud.asop.tools;

import io.r2dbc.spi.Row;

import java.lang.reflect.Method;
import java.util.Arrays;

public class BeanReflectUtil {
    public static <T> T ckRowToBean(Class<T> clazz, Row row) throws Exception {
        T objectCopy = clazz.getConstructor(new Class[] {}).newInstance();
        Arrays.stream(clazz.getDeclaredFields()).forEach(field -> {
            String fieldName = field.getName();
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String setMethodName = "set" + firstLetter  + fieldName.substring(1);
            Method setMethod;
            try {
                setMethod = clazz.getMethod(setMethodName,
                        field.getType());
                setMethod.invoke(objectCopy, row.get(fieldName, field.getType()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        return objectCopy;
    }
}
